import AgoraRTM from "./libs/agora-rtm-sdk-1.4.3.js"

let rtm = {
	client:null,
	channel:null
}

// 申请的appID
const appID = "149f7636178140d5821bf0d2b61a480b";

// 初始化客户端
const agoraFunction = function(that,options){
	rtm.client = AgoraRTM.createInstance(appID)
	// 创建cannel实例
	rtm.channel = rtm.client.createChannel(options.channelName)
	// 开始监听
	Listening(that)
	// 用户登录
	rtm.client.login(options).then((res)=>{
		rtm.channel.join().then(()=>{
			console.log('加入频道'+options.channelName+'成功')
		}).catch(error=>{
			console.log(error)
		})
	})
}

const Listening = function(that){
	// 监听用户连接状态
	rtm.client.on("ConnectionStateChanged",function(state,reason){
		console.log(state,reason)
	})
	// 显示对端发送的消息
	rtm.client.on("MessageFromPeer",function(message,peerId){
		var new_message = JSON.parse(message.text)
		console.log(new_message)
		if(new_message.data.type==4){
			that.startMic()
		}else if(new_message.data.type==5){
			that.breakMic()
		}else if(new_message.data.type==2){
			that.$u.toast("拒绝了你的申请")
		}
	});
	// 监听频道消息
	rtm.channel.on("ChannelMessage",function(message, memberId){
		var new_message = JSON.parse(message.text)
		console.log(new_message)
		if(new_message.cmd==1){ //聊天消息
			var msgSource = {
				text:new_message.data.message,
				type:new_message.data.type,
				user_name:new_message.data.userName,
				user_avatar:new_message.data.userAvatar,
				userId:memberId
			}
			if(msgSource.text!=undefined){
				that.getMsg(msgSource)
			}
		}else if(new_message.cmd==4){
			if(new_message.data.length<=1){
				that.isOwn = false
				that.isOccupy = false
			}
			new_message.data.forEach((el,index)=>{
				if(el.uid==that.agora_rtm.uid){
					var host_msg = el
					that.control(host_msg)
				}
				if(el.role==1){
					that.roleControl(el)
				}
			})
		}else if(new_message.cmd==3){
			that.allControl(new_message.data)
		}
		
	});
	// 监听用户加入频道事件
	rtm.channel.on("MemberJoined",function(memberId ){
		console.log(memberId+"加入频道")
	});
	// 监听用户离开频道事件
	rtm.channel.on("MemberLeft",function(memberId ){
		console.log(memberId+"离开频道")
	});
	rtm.channel.on("AttributesUpdated",function(attributes){
		if(attributes.data.value=="host"){
			that.changeOccupy(attributes.data.value)
		}else if(attributes.data.value=="audience"){
			that.changeOccupy(attributes.data.value)
		}
	})
}

const loginOut = function(){
	rtm.client.logout()
}

// 发送频道消息
const sendMsg = function(text){
	rtm.channel.sendMessage({text:text}).then(()=>{
		console.log('发送消息成功')
	}).catch(error=>{
		console.log(error,'发送消息失败')
	})
}

// 对指定用户发送消息
const sendMsgToPeer = function(body,peerId){
	rtm.client.sendMessageToPeer({
	      text: body
	    }, peerId, {
	      enableHistoricalMessaging: true
	    }).then(res=>{
			console.log(res)
		}).catch(err=>{
			console.log(err)
		});
}

export default {
	agoraFunction,
	loginOut,
	sendMsg,
	sendMsgToPeer,
	rtm
}
